import Vue from 'vue'
import observeSession from './observe'

Vue.prototype.$observe = observeSession // 全局订阅者
// 计算表格高度函数
Vue.prototype.getTableHeight = function ({searchHeight = 12, toolBarHeight = 50, pageHeight = 40, offHeight = 30}) {
  let winHeight = window.innerHeight
  if (!winHeight) {
    winHeight = document.documentElement.clientHeight
  }
  /*if (this.$store.state.cssProperty.mainMinHeight > winHeight - headerHeight) {
    winHeight = this.$store.state.cssProperty.mainMinHeight + headerHeight
  }*/
  let mainPadding = 57
  return winHeight - mainPadding - mainPadding - searchHeight - toolBarHeight - pageHeight - offHeight
}

// 获取列表的验证 验证规则模型数据
Vue.prototype.getGetListRulesModel = function (array) {
  let model = {}
  if (!array || !Array.isArray(array) || array.length === 0) {
    return model
  }
  array.map((item, index) => {
    for (var attr in item) {
      model[attr + index] = item[attr]
    }
  })
  return model
}

// 验证列表重复数据
Vue.prototype.checkRepeatListData = function (array, keys, message) {
  let keysData = []
  let result = true
  array.map(item => {
    /*
    根据keys 取到对应的值。
     */
    let value = null
    keys.map(key => {
      if (!value) {
        value = item[key]
      } else {
        value = value + item[key]
      }
    })
    let valueInKesData = keysData.find(data => data === value)
    if (!valueInKesData) {
      /*
      如果原来没有 就直接添加进去，
       */
      keysData.push(value)
    } else {
      /*
      如果有就说明这个值重复了,验证不通过
       */
      result = false
    }
  })
  if (!result) {
    this.$message({
      type: 'warning',
      message: message
    })
  }
  return result
}

// 设置表格各行颜色
Vue.prototype.tableRowClassName = function ({row, rowIndex}) {
  if (rowIndex === 1) {
    return 'warning-row'
  } else if (rowIndex === 3) {
    return 'success-row'
  }
  return ''
}

// 通过 标识判断是否有权限
Vue.prototype.canLoadButtonByIdentify = function (identification) {
  this.logonData = Vue.prototype.getLogonUserInfo()
  if (this.logonData && this.logonData.superAdmin) {
    return true
  }
  if (this.logonData && this.logonData.resources) {
    var resources = this.logonData.resources.filter(i => i.type === 'BUTTON')
    if (resources) {
      var hasPermission = resources.find(i => i.identification === identification)
      if (hasPermission) {
        return true
      }
    }
  }
  return false
}

// 通过 id判断是否有权限
Vue.prototype.hasPermission = function (id) {
  this.logonData = Vue.prototype.getLogonUserInfo()
  if (this.logonData && this.logonData.superAdmin) {
    return true
  }
  if (this.logonData && this.logonData.resources) {
    var resources = this.logonData.resources
    var hasPermission = resources.find(i => i.id === id)
    if (hasPermission) {
      return true
    }
  }
  return false
}

Vue.prototype.inputCheck = function (val, type, length) {
  if (type === 'MOB') {
    val = val.replace(new RegExp(/[^\d]/g), '').replace(/^[^1][\d]*/i, '')
    length = 11
  } else if (type === 'TEL') {
    val = val.replace(new RegExp(/[^\d-]/g), '')
    if (/^1.*/.test(val)) {
      length = 11
    } else {
      length = 13
    }
  } else if (type) {
    let regTemp = type.replace(/NUM/, '\\d').replace(/EN/, 'a-zA-Z').replace(/ZH/, '\\u4E00-\\u9FA5').replace(/FH/, '`~!@#$%^&*()_\\-+=<>?:"{}|,.\\/;\'\\\\[\\]').replace(/AFH/, '`~!@#$%^&*()_\\-+=<>?:"{}|,.\\/;\'\\\\[\\]·~！@#￥%……&*（）——\\-+={}|《》？：“”【】、；‘’，。、')
    let reg = new RegExp(`[^${regTemp}]`, 'g')
    val = val.replace(reg, '')
    if (type.includes(' ')) {
      val = val.replace(/^\s+/g, '')
    }
  } else {
    val = val.replace(/^\s+/g, '')
  }
  if (length) {
    let lengthReg = new RegExp('^(.{0,' + length + '}).*$')
    val = val.replace(lengthReg, '$1')
  }
  return val
}

Vue.prototype.removeEndSpace = function (val) {
  return val.replace(/\s+$/, '')
}

Vue.prototype.inputNum = function (val, decimalPlace = 0, intLength) {
  let reg = new RegExp(`[^${'\\d.'}]`, 'g')
  val = val.replace(reg, '')
  if (decimalPlace === 0) {
    val = val.replace(/[^\d]/g, '')
  } else {
    val = val.replace(/[^\d.]/g, '')
  }
  if (val === '') {
    return val
  }

  if (val.includes('.')) {
    let intStr = Number(val.split('.')[0]).toString()
    let decimalStr = val.split('.')[1].replace(new RegExp(`([\\d]{${decimalPlace}}).*`), '$1')
    if (intLength && intStr.length > intLength) {
      val = intStr.replace(new RegExp(`([\\d]{${intLength}}).*`), '$1')
    } else {
      val = intStr + '.' + decimalStr
    }
  } else {
    if (intLength) {
      val = val.replace(new RegExp(`([\\d]{${intLength}}).*`), '$1')
    }
    val = Number(val)
  }
  return val
}
Vue.prototype.inputMinusNum = function (val, decimalPlace = 0, intLength) {
  if (val === '-') {
    return val
  }
  let isFushu = false
  if (/^-.*/.test(val)) {
    isFushu = true
  }
  if (decimalPlace === 0) {
    val = val.replace(/[^\d]/g, '')
  } else {
    val = val.replace(/[^\d.]/g, '')
  }
  if (val === '') {
    return val
  }
  if (val.includes('.')) {
    let intStr = Number(val.split('.')[0]).toString()
    let decimalStr = val.split('.')[1].replace(new RegExp(`([\\d]{${decimalPlace}}).*`), '$1')
    if (intLength && intStr.length > intLength) {
      val = intStr.replace(new RegExp(`([\\d]{${intLength}}).*`), '$1')
    } else {
      val = intStr + '.' + decimalStr
    }
    val = intStr + '.' + decimalStr
  } else {
    if (intLength) {
      val = val.replace(new RegExp(`([\\d]{${intLength}}).*`), '$1')
    }
    // val = Number(val)
  }
  return isFushu ? 0 - val : val
}

Vue.prototype.validateSelect = function (list = [], selectOne, btnName) {
  let status = false
  let msg = ''
  if (list.length < 1) {
    msg = '至少选择一行数据'
    status = true
  } else if (selectOne && list.length > 1) {
    let temp = btnName || '修改'
    msg = `不能同时${temp}多条数据`
    status = true
  }
  if (status) {
    this.$message({
      message: msg,
      type: 'warning'
    })
  }
  return status
}

Vue.prototype.validateDate = function (startDate, endDate, name) {
  if (!startDate && !endDate) {
    return true
  }
  var today = new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1)
  var dateEndTime
  if (endDate) {
    endDate = endDate.replace(/-/g, '/')
    dateEndTime = new Date(endDate)
    if (dateEndTime.getTime() > today.getTime()) {
      this.$message({
        message: name + '的结束时间不能大于当天23:59:59',
        type: 'warning'
      })
      return false
    }
  }
  var dateStartTime
  if (startDate) {
    startDate = startDate.replace(/-/g, '/')
    dateStartTime = new Date(startDate)
    if (dateStartTime.getTime() > today.getTime()) {
      this.$message({
        message: name + '的开始时间不能大于当天23:59:59',
        type: 'warning'
      })
      return false
    }
  }
  if (dateStartTime && dateEndTime) {
    if (dateStartTime.getTime() > dateEndTime.getTime()) {
      this.$message({
        message: name + '的开始时间不能大于结束时间',
        type: 'warning'
      })
      return false
    }
  }
  return true
}

String.prototype.check = function (type, length) {
  console.log('===================', this)
  let val = this || ''
  if (type === 'MOB') {
    val = val.replace(new RegExp(/[^\d]/g), '').replace(/^[^1][\d]*/i, '')
  } else if (type === 'TEL') {
    val = val.replace(new RegExp(/[^\d-]/g), '').replace(/-+/g, '-').replace(/^-/g, '')
  } else if (type) {
    let regTemp = type.replace(/NUM/, '\\d').replace(/EN/, 'a-zA-Z').replace(/ZH/, '\\u4E00-\\u9FA5').replace(/FH/, '`~!@#$%^&*()_\\-+=<>?:"{}|,.\\/;\'\\\\[\\]').replace(/AFH/, '`~!@#$%^&*()_\\-+=<>?:"{}|,.\\/;\'\\\\[\\]·~！@#￥%……&*（）——\\-+={}|《》？：“”【】、；‘’，。、')
    let reg = new RegExp(`[^${regTemp}]`, 'g')
    val = val.replace(reg, '')
    if (type.includes(' ')) {
      val = val.replace(/^\s+/g, '')
    }
  }
  if (length) {
    let lengthReg = new RegExp('^(.{0,' + length + '}).*$')
    val = val.replace(lengthReg, '$1')
  }
  return val
}
String.prototype.mob = function () {
  return this.replace(new RegExp(/[^\d]/g), '').replace(/^[^1][\d]*/i, '').replace(/(1[\d]{10}).*/, '$1')
}
String.prototype.tel = function () {
  return this.replace(new RegExp(/[^\d-]/g), '').replace(/-+/g, '-').replace(/^-/g, '')
}
String.prototype.decimal = function (decimalPlace = 2) {
  let val = this.replace(/[^\d.]/g, '')
  if (val.includes('.')) {
    val = Number(val.split('.')[0]) + '.' + val.split('.')[1].replace(new RegExp(`([\\d]{${decimalPlace}}).*`), '$1')
  } else {
    val = Number(val)
  }
  return val
}
Vue.prototype.copyDeep = function (data) {
  return JSON.parse(JSON.stringify(data))
}
Vue.prototype.commExportExcel = function (url, data, fileName, fileData) {
  let userInfo = Vue.prototype.getLogonUserInfo()
  let token = userInfo.token
  // let dataSource = process.env.HOST + url
  // let exportUrl = process.env.HOST + '/excel/export?tmsToken=' + token
  let exportUrl = process.env.HOST + url + '?token=' + token
  // exportUrl  += '&fileName=' + fileName + '.xlsx'
  // exportUrl  += '&datasource=' + encodeURI(dataSource)
  exportUrl += '&datasourceParam=' + encodeURI(JSON.stringify(data))
  exportUrl += '&headerArray=' + encodeURI(JSON.stringify(fileData))
  window.open(exportUrl)
}
// 获得导出表头
Vue.prototype.exportExcelFeader = function ({colTable, fixed, fixedFeader, mapping}) {
  let tableData1 = []
  let property = []
  tableData1 = JSON.parse(JSON.stringify(colTable))
  tableData1.forEach(value => {
    if (mapping && mapping[value.prop]) {
      property.push(mapping[value.prop])
    } else {
      property.push(value.prop)
    }
  })
  let fixedList = fixed || fixedFeader
  if (fixedList) {
    property = [...fixedList, ...property]
  }
  return property
}
Vue.prototype.getCommSummaries = function ({column, customer, title = '合计', titleIndex}) {
  return function (param) {
    const sums = []
    const {columns, data} = param
    columns.forEach((columnItem, index) => {
      if ((titleIndex === undefined && columnItem.type === 'index') || index === titleIndex) {
        sums[index] = title
      } else if (customer) {
        sums[index] = customer[columnItem.property] === null || customer[columnItem.property] === undefined || customer[columnItem.property] === '' ? '-' : customer[columnItem.property]
      } else {
        let sumList = []
        column.forEach((e) => {
          if (e.toString().includes('-')) {
            for (let i = Number(e.split('-')[0]); i <= Number(e.split('-')[1]); i++) {
              sumList.push(i)
            }
          } else {
            sumList.push(Number(e))
          }
        })
        if (sumList.includes(index)) {
          const values = data.map(e => Number(e[columnItem.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] += ''
          } else {
            sums[index] = '-'
          }
        }
      }
    })

    return sums
  }
}
// pl table data 改变前 执行
Vue.prototype.tableScrollTopLeft = function (ref = 'tableData', scroll = {}) {
  let left = this.$refs[ref] && this.$refs[ref].$el.querySelector('.el-table__body-wrapper') && this.$refs[ref].$el.querySelector('.el-table__body-wrapper').scrollLeft
  let self = this
  setTimeout(function () {
    self.$refs[ref] && self.$refs[ref].pagingScrollTopLeft(scroll.top, (scroll.left || left))
  }, 100)
}
// element table row click 选中当前行
Vue.prototype.tableRowClick = function (row, col, event, ref, except = []) {
  if (row && (col && !except.includes(col.property))) {
    this.$refs[ref].toggleRowSelection([{ row: row}])
  }
}
Vue.prototype.tableRowClickE = function (row, col, event, ref, except = []) {
  if (!except.includes(col.property)) {
    this.$refs[ref].toggleRowSelection(row)
  }
}
// 计算dom高度
Vue.prototype.autoDomHeight = function (tableId, otherHeight = 0) {
  let self = this
  let domTemp = document.getElementById(tableId)
  let heightTop = domTemp ? domTemp.getBoundingClientRect().top : 200
  let height = self.$store.state.common.windowSize.height - heightTop - 10 - otherHeight
  setTimeout(function () {
    if (document.getElementById(tableId)) {
      if (!domTemp) {
        domTemp = document.getElementById(tableId)
        heightTop = domTemp ? domTemp.getBoundingClientRect().top : 200
        height = self.$store.state.common.windowSize.height - heightTop - 10 - otherHeight
        domTemp.parentElement.style.height = height + 'px'
      }
    }
  }, 300)
  return height
}
// 计算table高度
Vue.prototype.autoTableHeight = function (tableId, otherHeight = 0) {
  let self = this
  let ref = (this.$refs && this.$refs[tableId] && this.$refs[tableId])
  let domTemp = ref ? ref.$el : ''
  let heightTop = domTemp ? domTemp.getBoundingClientRect().top : 200
  let height = self.$store.state.common.windowSize.height - heightTop - 15 - otherHeight
  setTimeout(function () {
    if (self.$refs && self.$refs[tableId] && self.$refs[tableId].setHeight) {
      if (!domTemp) {
        domTemp = self.$refs[tableId].$el
        heightTop = domTemp ? domTemp.getBoundingClientRect().top : 200
        height = self.$store.state.common.windowSize.height - heightTop - 15 - otherHeight
        height = height > 200 ? height : 200
        domTemp.parentElement.style.height = height + 'px'
      }
      self.$refs[tableId].setHeight()
      self.$refs[tableId].doLayout && self.$refs[tableId].doLayout()
    }
  }, 300)
  if (!height || height < 200) {
    height = 200
  }
  return height
}
Vue.prototype.getTreeInfo = function (treeList, value, key = 'id') {
  let current = null
  // 遍历树获得所有匹配元素
  const getSearchList = (item) => {
    item.forEach((e) => {
      if (e[key] === value) {
        current = JSON.parse(JSON.stringify(e))
      }
      if (!current) {
        let children = e.children
        if (children && children.length > 0) {
          getSearchList(children)
        }
      }
    })
  }
  getSearchList(treeList)
  return current
}
// tree 默认展开
Vue.prototype.treeExpands = function ({list, key, childKey = 'children', depth = 1, other}) {
  let expandList = []
  let tierTemp = 1
  // console.log('treeExpands' + depth, list);
  const getExpand = (item) => {
    item.forEach((e) => {
      expandList.push(e[key])
      let children = e[childKey]
      // console.log('children', children);
      if (tierTemp < depth && children && children.length > 0) {
        tierTemp++
        getExpand(children)
      }
    })
    tierTemp--
  }
  getExpand(list)
  if (other) {
    expandList = expandList.concat(other)
  }
  return expandList
}
// mapping 排序
Vue.prototype.getSortData = function (data) {
  if (data.prop && data.order) {
    const sortType = {ascending: 'ASC', descending: 'DESC'}
    return {
      'prop': data.prop,
      'type': sortType[data.order]
    }
  }
  return {}
}
// 获取登录信息
Vue.prototype.getLogonUserInfo = function () {
  let key = Vue.prototype.keys.userInfo
  return JSON.parse(sessionStorage.getItem(key) || '{}')
}
// 保存登录信息
Vue.prototype.setLogonUserInfo = function (data) {
  if (data) {
    let key = Vue.prototype.keys.userInfo
    return sessionStorage.setItem(key, JSON.stringify(data))
  }
}
// 清除登录信息
Vue.prototype.removeLogonUserInfo = function () {
  let key = Vue.prototype.keys.userInfo
  return sessionStorage.removeItem(key)
}
Vue.prototype.getOrgList = function (list, multiple) {
  let select = []
  list.forEach(item => {
    select.push(item[item.length - 1])
  })
  if (multiple) {
    return select
  } else {
    return select[0] || ''
  }
}
Vue.prototype.getCascaderSelect = function (list, ids, key = 'id') {
  let selectList = []
  let current = []
  // 遍历树获得所有匹配元素
  const getList = (item) => {
    item.forEach((e) => {
      current.push(e[key])
      if (ids.includes(e[key])) {
        selectList.push(JSON.parse(JSON.stringify(current)))
      }
      let children = e.children
      if (children && children.length > 0) {
        getList(children)
      }
      current = current.slice(0, current.length - 1)
    })
  }
  getList(list)
  return selectList
}
Vue.prototype.getTableConfig = function (all, showKey, hideKey) {
  let tableData = this.copyDeep(all)
  if (localStorage.getItem(showKey)) {
    let showTable = JSON.parse(localStorage.getItem(showKey) || '[]')
    let hideTable = JSON.parse(localStorage.getItem(hideKey) || '[]')
    const getIndex = function (list, item) {
      for (let i = 0; i < list.length; i++) {
        if (list[i].prop === item.prop) {
          return i
        }
      }
      return -1
    }
    let showTemp = []
    let hideTemp = []
    hideTable.forEach((item) => {
      let index = getIndex(tableData, item)
      if (index >= 0) {
        hideTemp.push(Object.assign(tableData[index], {width: item.width}))
        tableData.splice(index, 1)
      }
    })
    showTable.forEach((item) => {
      let index = getIndex(tableData, item)
      if (index >= 0) {
        showTemp.push(Object.assign(tableData[index], {width: item.width}))
        tableData.splice(index, 1)
      }
    })
    if (tableData.length > 0) {
      showTemp = showTemp.concat(tableData)
    }
    return {show: showTemp, hide: hideTemp}
  } else {
    return {show: tableData, hide: []}
  }
}
Vue.prototype.downloadFile = function (filePath) {
  if (/.*(.png|.jpg|.mp3|.mp4|.html|.pdf|.avi|.mkv|.txt|.js|.jpeg|.gif|.tif|.bmp|.mov|.rmvb|.rm|.3gp|.flv)$/.test(filePath)) {
    let loadinginstace = Vue.prototype.$loading({lock: true, text: '正在处理文件，请稍后...', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.0)'})
    fetch(filePath).then(res => res.blob()).then(blob => {
      const a = document.createElement('a')
      document.body.appendChild(a)
      a.style.display = 'none'
      // 使用获取到的blob对象创建的url
      const url = window.URL.createObjectURL(blob)
      a.href = url
      // 指定下载的文件名
      a.download = filePath.replace(/.*\/([^/]*)$/, '$1')
      a.click()
      document.body.removeChild(a)
      // 移除blob对象的url
      window.URL.revokeObjectURL(url)
      loadinginstace.close()
    })
  } else {
    window.open(filePath)
  }
}
Vue.prototype.vehicleTypeRef = localStorage.getItem('vehicleTypeRef') ? JSON.parse(localStorage.getItem('vehicleTypeRef')) : []
Vue.prototype.getVehicleType = function () {
  this.$http.post('/billingDriverGeo/vehicles')
    .then(function (res) {
      let vehicleTypeRef = res.data.data
      vehicleTypeRef.map((item) => {
        item.value = item.vhType
        item.label = item.name
      })
      localStorage.setItem('vehicleTypeRef', JSON.stringify(vehicleTypeRef))
      Vue.prototype.vehicleTypeRef = vehicleTypeRef
    }).catch(function (error) {
      console.log(error)
    })
}
Vue.prototype.getIsPayment = function ({orderNo, url, orderId}) {
  // 开单时候的付款方式
  let self = this
  return new Promise(function (resolve, reject) {
    self.$http.post(url, {orderNo: orderNo, orderId: orderId})
    .then(function (res) {
      if (res.data.code === '0000') {
        resolve(res)
      }
    }).catch(function (err) {
      reject(err)
    })
  })
}
// 获取预打印列表
Vue.prototype.getPrePrintOrder = function () {
  return JSON.parse(sessionStorage.getItem('prePrintOrder') || '[]')
}
// 检查预打印列表入存在去掉返回true 负责返回 false
Vue.prototype.checkPrePrintOrder = function (order) {
  let prePrint = JSON.parse(sessionStorage.getItem('prePrintOrder') || '[]')
  console.log('checkPrePrintOrder order: ', prePrint)
  let prePrintC = prePrint.filter((item) => {
    return item.order === order
  })[0]
  if (!prePrintC) {
    return false
  }
  prePrint = prePrint.filter((item) => {
    return item.order !== order
  })
  console.log('checkPrePrintOrder order1: ', prePrint)
  sessionStorage.setItem('prePrintOrder', JSON.stringify(prePrint))
  return prePrintC
}
// 添加到预打印列表
Vue.prototype.addPrePrintOrder = function (orderData) {
  let prePrint = JSON.parse(sessionStorage.getItem('prePrintOrder') || '[]')
  prePrint = prePrint.filter((item) => {
    return item.order !== orderData.order
  })
  prePrint.push(orderData)
  console.log('addPrePrintOrder order: ', prePrint)
  return sessionStorage.setItem('prePrintOrder', JSON.stringify(prePrint))
}
Vue.prototype.getOrderDetailComm = function ({orderNo, tempOrder}) {
  let self = this
  return new Promise(function (resolve, reject) {
    self.$http.post('/order/orderDetail', {orderNumber: orderNo, tempOrder: tempOrder})
      .then(function (res) {
        if (res.data.code === '0000') {
          resolve(res)
        } else {
          reject(res)
        }
      }).catch(function (err) {
        reject(err)
      })
  })
}
var orderNoInputTimeOut = null
Vue.prototype.isOrderNo = function (orderNo, callback, timeout = 500) {
  let isOrder = /^(B)?(HD|YF)?(\d{7}|\d{12})(\d{3})?$/.test(orderNo)
  orderNoInputTimeOut && clearTimeout(orderNoInputTimeOut)
  if (isOrder && callback) {
    orderNoInputTimeOut = setTimeout(function () {
      callback()
    }, timeout)
  }
  return isOrder
}

export default Vue
